<?php
/**
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2020/9/7
 * Time: 11:33 AM
 */

namespace Util\KuaiDi100;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Factory;

class Query
{

    // 基础域名
    private $baseUrl = '';

    // 公司编号
    private $customer = '';
    // 授权KEY
    private $key = '';

    // 实时查询物流信息缓存key
    private $pollQueryKey = 'kuaidi100PollQuery';


    public function __construct($customer='', $key = '')
    {
        $this->customer = $customer;
        $this->key      = $key;
    }

    /**
     * 实时查询
     * 官方文档地址: https://api.kuaidi100.com/manager/page/document/synquery
     */
    public function pollQuery($params)
    {
        $postData = [
            'customer' => $this->customer,
            'param'    => [
                'com' => strtolower($params['com']), // 查询的快递公司的编码，一律用小写字母
                'num' => $params['num'], // 查询的快递单号
                'phone' => $params['phone'], // 收件人或寄件人的手机号或固话
            ],
        ];

        foreach ($postData['param'] as $key => $value){
            if(empty($value)){
                return ResultWrapper::fail($key.'参数为空', ErrorCode::$paramError);
            }
        }

        $postData['param'] = json_encode($postData['param']);
        $postData['sign']  = strtoupper(md5($postData['param'].$this->key.$postData['customer'])); // 签名

        $pollQueryData = Factory::cache('default')->get($this->pollQueryKey.':'.$params['num']);
        if (!empty($pollQueryData)) {
            return ResultWrapper::success($pollQueryData);
        }

        $response = request('https://poll.kuaidi100.com/poll/query.do', $postData, 30,  true);

        if ($response['httpcode'] != 200) {
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }
        $responseData = json_decode($response['content'], true);

        if($responseData['message'] != 'ok'){
            return ResultWrapper::fail($responseData['message'], $responseData['returnCode']);
        }

        Factory::cache('default')->set($this->pollQueryKey . ':' . $params['num'], $response['content'], 3600);
        return ResultWrapper::success($response['content']);

    }

    // 快递单当前状态
    public function getState($state)
    {
       $satateData = [
           0 => '在途',
           1 => '揽收',
           2 => '疑难',
           3 => '签收',
           4 => '退签',
           5 => '派件',
           6 => '退回',
           7 => '转投',
           10 => '待清关',
           11 => '清关中',
           12 => '已清关',
           13 => '清关异常',
           14 => '拒签'
       ];

       return isset($satateData[$state]) ? $satateData[$state] : '';
    }
}